<template>
    <ul :id="id" class="ztree"></ul>
</template>

<script>
	export default {
		name: "Ztree",
        props: ['id', 'data'],
        data() {
		    let $this = this;
		    return {
		        zTreeObj: undefined,
		        setting: {
                    view: {
                        selectedMulti: false
                    },
                    check: {
                        enable: true,
                    },
                    data: {
                        simpleData: {
                            enable: true
                        }
                    },
                    edit: {
                        enable: false
                    },
                    callback: {
                        onClick: function (e, treeId, treeNode, clickFlag) {
                            $this.zTreeObj.checkNode(treeNode, !treeNode.checked, true);
                            let nodes = $this.zTreeObj.getCheckedNodes(true);
                            $this.$emit('handleCheckChange', nodes);
                        }
                    }
                }
            };
        },
        watch: {
		    data() {
                this.initData();
            }
        },
        mounted () {
		    this.initData();
        },
        methods: {
		    initData() {
                let $this = this;
                let list = $this.resetTreeData(this.data);
                $this.zTreeObj = $.fn.zTree.init($('#' + $this.id), $this.setting, list);
                $this.zTreeObj.expandAll(true);
            },
            resetTreeData(list) {
                let $this = this;
                if (list && list.length > 0) {
                    let data = [];
                    list.forEach(item => {
                        let obj = {};
                        obj.id = item.sid;
                        obj.pId = item.parent_sid;
                        obj.name = item.name;
                        // obj.opened = true;
                        if (item.children && item.children.length > 0) {
                            obj.children = $this.resetTreeData(item.children);
                        }
                        data.push(obj);
                    });
                    return data;
                } else {
                    return [];
                }
            },
        }
	}
</script>

<style lang="less" rel="stylesheet/less" scoped>
    .ztree {
    }
</style>
